from django.shortcuts import render, redirect, HttpResponse


def login_required(func):
    def inner(request, *args, **kwargs):
        # 读取cookie
        is_login = request.COOKIES.get('is_login')
        # 获取session
        is_login = request.session.get('is_login')
        print(request.session.session_key)


        # is_login = request.get_signed_cookie('is_login',default='',salt='s23')

        # 判断是否登陆
        if is_login != '1000':
            return redirect('/login/?returnurl={}'.format(request.path_info))
        ret = func(request, *args, **kwargs)
        return ret

    return inner


# Create your views here.
def login(request):
    request.session.clear_expired()
    if request.method == 'POST':
        user = request.POST.get('user')
        pwd = request.POST.get('pwd')
        # 校验成功设置登陆状态

        if user == 'alex' and pwd == '123':
            # 获取是否有要跳转的地址
            returnurl = request.GET.get('returnurl')
            if returnurl:
                ret = redirect(returnurl)
            else:
                ret = redirect('/home/')
            # 设置cookie
            # ret['Set-Cookie'] = 'is_login=1000; path=/'
            # ret.set_cookie('is_login', '1000',)  # Set-Cookie: is_login=1
            # ret.set_signed_cookie('is_login', '1000', 's23')  # Set-Cookie: is_login=1
            # 设置session

            request.session['is_login'] ='1000'
            request.session['user'] ='alex'
            # request.session.set_expiry(20)
            return ret
        return render(request, 'login.html', {'error': '用户名或密码错误'})

    return render(request, 'login.html')


@login_required
def home(request):
    return HttpResponse('home ok')


@login_required
def index(request):
    return HttpResponse('index ok')


def logout(request):
    # 删除is_login
    ret = redirect('/login/')
    # ret.delete_cookie('is_login')
    request.session.delete()
    # request.session.flush()
    return ret
